var userService = require('../../service/userService');
var util = require("util")
var md5 = require("md5");

/**
 * 用户控制器 
 * Author: 梦里小白龙 <jiangwenshu1990@126.com> <http://www.jz07.cn>
 */

module.exports  = {
    //添加用户信息
    save(req, res, next){
        let user_name = req.body.user_name ||'';
        let sex  = req.body.sex || '';
        if(!user_name && !req.body.password){
            res.json({code:2004 ,msg:'参数错误'})
        }
        let params = {
            user_name:user_name,
            password:md5(req.body.password),
            token:Date.now(),
            sex:sex,
            reg_time:parseInt(Date.now()/1000)
        }
        //判断用户是否已经注册
        userService.checkName(user_name).then(response=>{
            if(response.length >= 1){
                res.json({code:-1 ,msg:'该用户名已经被注册'})
            }else{
                //添加用户信息
                userService.save(params).then(data=>{
                    data ? res.json({code:1 ,msg:'添加成功'}) : res.json({code:0 ,msg:'添加失败'});
                });
            }

        })
    },
    //修改数据
    update(req, res, next){
        let params = {
            user_name: req.body.user_name,
            password: md5(req.body.password),
            sex: req.body.sex,
            id: req.body.id
        }
        
        //修改用户信息
        userService.update(params).then(data=>{
            data ? res.json({code:1 ,msg:'修改成功'}) : res.json({code:0 ,msg:'修改失败'});
        })
    },
    //查询用户信息
    getById(req, res, next){

        //查询用户信息
        userService.getById(req.body.id).then(data=>{
            data ? res.json({code:1 ,msg:'修改成功',info: data}) : res.json({code:0 ,msg:'修改失败'});
        })
    },
    //删除数据
    delete(req, res, next){
        if(req.body.id==1){
            res.send({code:1001 ,msg:'超级管理员无法删除'});
        }else{
            //删除用户信息
            userService.udelete(req.body.id).then(data=>{
                data ? res.json({code:1 ,msg:'删除成功'}) : res.json({code:0 ,msg:'删除失败'});
            }) 
        }
 
    },
    //显示所有数据
    lists(req, res, next){
        var params ={
            page:parseInt(req.body.page),  //分页页数
            size:parseInt(req.body.size),  //当页总数
            user_name:req.body.user_name,   //查询名称
        }  
        console.log("lists",params);
        userService.lists(params).then(data=>{
            res.json({code:1 ,msg:'查询成功',data:{lists:data.data,page:data.page,count:data.count}});
        })
    },
    //用户登录
    login(req, res, next){
        let user_name = req.body.user_name;
        let password = req.body.password;
		console.log("user_name:"+user_name+"password:"+password);
        //用户信息登录
        userService.login(user_name,password).then(data=>{
            if(data){
                req.session.user = data;
                res.json({code:1 ,msg:'登录成功',data:data});
            }else{
                res.json({code:0 ,msg:'用户名或密码有误'});
            }
        })  
    }
} 